package cn.sdc.sfw.dao.handler.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.sdc.sfw.dao.handler.ResultSetHandler;
import cn.sdc.sfw.dao.model.ResultMap;
import cn.sdc.sfw.dao.model.PropertyType;

public class MapResultSetHandlerImpl implements ResultSetHandler {

	private Boolean listFlg;
	
	public MapResultSetHandlerImpl() {
		this(false);
	}

	public MapResultSetHandlerImpl(Boolean listFlg) {
		this.listFlg = listFlg;
	}
	
	protected Map createRow(ResultSet rs, PropertyType[] propertyTypes)
			throws SQLException {

		Map row = new ResultMap();
		for (int i = 0; i < propertyTypes.length; ++i) {
			Object value = propertyTypes[i].getValueType().getValue(rs, i + 1);
			row.put(propertyTypes[i].getPropertyName(), value);
		}
		return row;
	}
	
	public Object handle(ResultSet resultSet) throws SQLException {
		if(listFlg){
			PropertyType[] propertyTypes = PropertyType
					.createPropertyTypes(resultSet.getMetaData());
			List list = new ArrayList();
			while (resultSet.next()) {
				list.add(createRow(resultSet, propertyTypes));
			}
			return list;
		}else if (resultSet.next()) {
			PropertyType[] propertyTypes = PropertyType
					.createPropertyTypes(resultSet.getMetaData());
			return createRow(resultSet, propertyTypes);
		} else {
			return null;
		}
	}
}